package com.lin.consumer;

import com.lin.util.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Controller
public class Demo3Consumer {
    private static String EXCHANGE_NAME;

    @Value("${queue.demo3_exchange_name}")
    public void  setQueueName(String exchangeName) {
        EXCHANGE_NAME = exchangeName;
    }

    public static void work(Integer id) throws Exception {
        Connection connection = RabbitUtil.getConnection();
        Channel channel = connection.createChannel();

//      创建一个自动销毁的队列
        String queueName = channel.queueDeclare().getQueue();
//      创建交换机
        channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
//      将队列绑定到交换机上
        channel.queueBind(queueName,EXCHANGE_NAME,"");

        System.out.println("listener"+id+" start to waiting for work!");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("listener"+id+" receive broadcast："+message);
        };
//      这里第二个参数设置成true可以自动回复ack
//        channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumeTag->{});
        channel.basicConsume(queueName,true,deliverCallback,consumeTag->{});
    }
}
